Add MCP server endpoint for AI agent doc access - #2727
Conversation
Adds POST /mcp implementing the Model Context Protocol (JSON-RPC 2.0, non-streaming HTTP) so AI coding agents can query a self-hosted DevDocs instance directly instead of scraping the browser UI. Three tools, all reading from the same public/docs tree the server already uses to serve doc content: - devdocs_list_docsets — the configured doc sets (from settings.docs) - devdocs_search — entries in one doc set matching a query (index.json) - devdocs_get_page — one entry's content as plain text, HTML stripped with Nokogiri (already a dependency) (db.json) Relates to freeCodeCamp#2420.
6312f7c to
ebe24b6
Compare
- Add pagination support (offset/limit) to reduce response size - Return condensed format (slug, name, version only) instead of full metadata - Add query parameter for filtering by slug or name (case-insensitive) - Include pagination metadata (offset, limit, total, returned) in responses - Add comprehensive unit tests for all new features (7 new test cases) All 11 MCP tests passing with 45 assertions. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
ebe24b6 to
37090e8
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Protocol interoperability, production storage, input security, and error-handling issues must be resolved.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds an MCP endpoint so coding agents can query current DevDocs content, addressing #2420.
Changes:
- Adds JSON-RPC initialization and tool discovery.
- Adds docset listing, search, and page retrieval tools.
- Adds MCP tests, fixtures, and local configuration exclusion.
File summaries
| File | Description |
|---|---|
.gitignore |
Excludes local MCP configuration. |
lib/app.rb |
Exposes the /mcp endpoint. |
lib/mcp/server.rb |
Implements MCP request handling and tools. |
test/mcp_test.rb |
Tests MCP operations. |
test/files/docs/mcp_fixture/index.json |
Provides search fixtures. |
test/files/docs/mcp_fixture/db.json |
Provides page-content fixtures. |
Review details
Suppressed comments (2)
lib/mcp/server.rb:126
- The hosted deployment provisions only
meta.jsonlocally (lib/tasks/docs.thor:263-266), notindex.json, so every hosteddevdocs_searchcall raisesENOENT. Use the configured documentation origin/storage backend or provision indexes during deployment.
index_path = File.join(app_settings.docs_path, slug, 'index.json')
index = JSON.parse(File.read(index_path))
lib/mcp/server.rb:126
- The public request's
slugcan contain.., allowing this join to escapedocs_pathand inspect an unrelatedindex.json. Validate the slug againstapp_settings.docsand enforce containment within the expanded documentation root.
def self.search_docset(app_settings, slug, query)
index_path = File.join(app_settings.docs_path, slug, 'index.json')
index = JSON.parse(File.read(index_path))
- Files reviewed: 5/6 changed files
- Comments generated: 9
- Review effort level: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| case request['method'] | ||
| when 'initialize' | ||
| respond(request, { | ||
| 'protocolVersion' => '2024-11-05', |
| db_path = File.join(app_settings.docs_path, slug, 'db.json') | ||
| db = JSON.parse(File.read(db_path)) |
| payload = JSON.parse(request.body.read) | ||
| Mcp::Server.handle(payload, settings).to_json |
| def self.call_tool(request, app_settings) | ||
| params = request['params'] | ||
| case params['name'] |
- Validate docset slugs against configured docs to prevent path traversal attacks - Handle missing index.json and db.json files gracefully in production - Return descriptive JSON-RPC errors when files are unavailable - Add tests for path traversal protection and missing file handling - Add mcp_fixture to test docs manifest for proper test coverage This addresses GitHub review concerns about: 1. Security: Path traversal vulnerability (slug with ..) 2. Production: Missing index.json and db.json in hosted deployments Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
- Add error boundary in /mcp endpoint to catch JSON parse errors (-32700) - Return JSON-RPC error instead of HTML 500 for parse failures - Handle unknown tool names with -32602 error instead of returning nil - Add generic error handler in Mcp::Server.handle for unexpected exceptions - Fixes issues where malformed requests would return HTML error pages Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
- Validate all arguments against tool inputSchema before dispatch - Check required fields are present - Validate field types (string, integer, number) - Enforce min/max constraints on numeric values - Return -32602 (invalid request) for validation failures - Add comprehensive tests for missing/invalid arguments and type mismatches Fixes comment about params being dereferenced without validation. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
- Replace simple Node#text concatenation with proper block element handling - Add line breaks before/after block elements (p, div, h1-h6, ul, ol, li, blockquote, pre, br) - Preserve meaningful whitespace while removing excess blank lines - Prevents adjacent block elements from concatenating without separation Fixes issue where <h1>Title</h1><p>Body</p> would become TitleBody. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
- Add offset and limit parameters to search (same as list_docsets) - Validate that query is non-empty to prevent matching everything - Return paginated results with metadata (offset, limit, total, returned) - Prevents large result sets from exceeding agent context limits - Add tests for pagination and empty query validation Fixes issue where large docsets could generate oversized responses. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
- Add DB_CACHE to cache parsed db.json files in memory - Load database once per docset and reuse across requests - Prevents reparsing multi-megabyte files on every page lookup - Reduces memory allocations and CPU overhead on concurrent calls - Cache key includes docs_path to handle test/production separation Fixes performance issue with repeated full-database parsing. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
- Verify malformed JSON returns -32700 parse error - Ensure /mcp endpoint returns JSON-RPC error instead of HTML 500 Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
The transport is not compatible with the advertised protocol, and production deployments lack the local indexes and databases required by the tools.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (1)
lib/mcp/server.rb:64
- A
2024-11-05client must sendnotifications/initializedafter initialization, but this falls through to-32601. Because that message has noid, JSON-RPC also forbids sending any response to it. Handle this notification and suppress the HTTP response body for notifications instead of returning an error withid: null.
else
error(request, -32601, "Unsupported method: #{request['method']}")
- Files reviewed: 6/7 changed files
- Comments generated: 7
- Review effort level: Balanced
| post '/mcp' do | ||
| content_type :json | ||
| begin | ||
| body = request.body.read | ||
| payload = JSON.parse(body) |
| cache_key = "#{app_settings.docs_path}:#{slug}" | ||
| return DB_CACHE[cache_key] if DB_CACHE.key?(cache_key) |
| db_path = File.join(app_settings.docs_path, slug, 'db.json') | ||
| unless File.exist?(db_path) | ||
| raise "Page database not available for #{slug}. Full content is served from the CDN." |
| index_path = File.join(app_settings.docs_path, slug, 'index.json') | ||
| unless File.exist?(index_path) | ||
| raise "Search index not available for #{slug}. The search index is served from the CDN." |
| params = request['params'] | ||
| tool_name = params['name'] | ||
| arguments = params['arguments'] || {} |
| if response.key?('error') | ||
| assert_equal(-32603, response['error']['code']) | ||
| assert_includes response['error']['message'].downcase, 'search index' | ||
| end |
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Joe Butler <6955350+joebutler2@users.noreply.github.com>
Entry paths carry a #fragment for entries that share a page (377 of 508 bash entries), but db.json is keyed by the page path alone, so the search -> get_page workflow failed with "Page not found".
Their tags were missing from block_element?, so tables and definition lists - most of the CSS and HTML reference content - collapsed into runs like "NameTypefooString".
Nokogiri's #traverse is post-order, so a block element's newline was
emitted after its text and text preceding the block ran into it
("Options are:one\ntwo").
Whitespace was collapsed over the whole document, flattening the indentation of <pre> blocks and corrupting code samples. Text is now collected in runs of equal preformattedness and only the ones outside <pre> are collapsed.
Every db.json value is also on disk as the .html file the app serves, so get_page reads that (~0.01ms) rather than parsing up to 100MB of JSON. This drops DB_CACHE, which pinned every db.json touched in memory (571MB across the docsets here) and served stale text after a re-scrape. The path comes from the caller, so it is now kept inside the docset.
index.json was re-read and re-parsed on every search (37ms for the largest one here). It is now cached per docset, keyed on mtime and size so a re-scrape is picked up. The indexes are small - 16.5MB for all 48 docsets here - unlike the db.json cache this replaces.
The loop above it already rejects every field that the schema does not declare, whatever additionalProperties says.
An array or scalar payload made the rescue handler itself raise a TypeError on request['id'], which escaped handle and surfaced as -32603 from the route. Batches and scalars now get -32600.
A call without params, or with non-object arguments, hit nil and
returned -32603 with a Ruby error message ("undefined method '[]' for
nil") instead of -32602.
A request without an id is a notification and must not be answered, but notifications/initialized - which every client sends right after the handshake - was answered with -32601 and a null id. Notifications now get 202 with an empty body.
A tool that cannot answer - an unknown slug, a missing page, an empty query - now returns its message as an isError result, which is what the MCP spec asks for: a protocol error is handled by the client and never reaches the model.
The assertions sat behind "if response.key?('error')", so the test
passed without checking anything if the error stopped being returned.
In keeping competitive with other API Doc services (like Dash), let's add MCP support so agents can interact with our Docs as well.
This adds
POST /mcpimplementing the Model Context Protocol (JSON-RPC 2.0, non-streaming HTTP) so AI coding agents can query a self-hosted DevDocs instance directly instead of scraping the browser UI.Three tools, all reading from the same public/docs tree the server already uses to serve doc content:
Relates to #2420.